<template id="paymentRequest-create">
  <!-- 采购付款申请抽屉 -->
  <v-navigation-drawer v-if="isCreateDrawerShown" v-model="isCreateDrawerShown" :permanent="isCreateDrawerShown" fixed
    temporary right width="80%" class="elevation-24">
    <v-form ref="createForm" lazy-validation>
      <!-- 抽屉标题 -->
      <v-row>
        <span class="text-subtitle-1 font-weight-medium pa-6 pl-7">{{ticketType}}申请-创建</span>
        <v-spacer></v-spacer>
        <!-- 抽屉操作按钮 -->
        <v-row class="justify-end mx-0 mt-6 px-8">
          <v-btn color="success" @click="doUiAction('createItem')" small>提交</v-btn>
          <v-btn class="elevation-0 ml-2" @click="isCreateDrawerShown = false" small>取消</v-btn>
        </v-row>
      </v-row>

      <!-- 抽屉内容 -->
      <v-expansion-panels accordion flat multiple v-model="expands">
        <v-expansion-panel v-for="order, index in orderList" :key="index">
          <v-card class="mx-4 mb-4" outlined>
            <v-expansion-panel-header>{{`【${order.ticketBizId}】${order.customerInfo.customerName ||
              ''}`}}</v-expansion-panel-header>
            <v-expansion-panel-content>

              <v-row class="mt-0">
                <v-col cols="12" sm="4" md="4">
                  <v-text-field class="jh-v-input" prefix="客户" dense single-line filled
                    v-model="order.customerInfo.customerName" :rules="validationRules.requireRules"></v-text-field>
                </v-col>
                <v-col cols="12" sm="4" md="4">
                  <v-text-field class="jh-v-input" prefix="付款账号" dense single-line filled
                    v-model="order.customerInfo.customerAccountNum"
                    :rules="validationRules.requireRules"></v-text-field>
                </v-col>
                <v-col cols="12" sm="4" md="4">
                  <v-text-field class="jh-v-input" prefix="所属银行" dense single-line filled
                    v-model="order.customerInfo.customerBankName" :rules="validationRules.requireRules"></v-text-field>
                </v-col>
                <v-col cols="12" sm="4" md="4">
                  <v-text-field class="jh-v-input" prefix="开户分行/支行" dense single-line filled
                    v-model="order.customerInfo.customerBranchBankName"
                    :rules="validationRules.requireRules"></v-text-field>
                </v-col>
                <v-col cols="12" sm="4" md="4">
                  <v-text-field class="jh-v-input" prefix="付款账期(天)" dense single-line filled
                    v-model="order.customerInfo.customerCollectionCycle"
                    :rules="validationRules.requireRules"></v-text-field>
                </v-col>
                <v-col cols="12" sm="4" md="4">
                  <v-text-field class="jh-v-input" prefix="地址" dense single-line filled
                    v-model="order.customerInfo.customerAddress"></v-text-field>
                </v-col>
                <v-col cols="12" sm="4" md="4">
                  <v-text-field class="jh-v-input" prefix="联系人" dense single-line filled
                    v-model="order.customerInfo.customerContactPerson"></v-text-field>
                </v-col>
                <v-col cols="12" sm="4" md="4">
                  <v-text-field class="jh-v-input" prefix="联系电话" dense single-line filled
                    v-model="order.customerInfo.customerPhoneNum"></v-text-field>
                </v-col>
                <v-col cols="12" sm="4" md="4">
                  <v-text-field class="jh-v-input" prefix="邮政编码" dense single-line filled
                    v-model="order.customerInfo.customerPostalCode"></v-text-field>
                </v-col>
                <v-col cols="12" sm="12" md="4">
                  <span class="jh-input-label">{{ticketType}}申请日期</span>
                  <v-menu :nudge-right="40" transition="scale-transition" offset-y min-width="auto">
                    <template v-slot:activator="{ on, attrs }">
                      <v-text-field :rules="validationRules.requireRules" dense single-line filled
                        v-model="order.paymentRequestAt" label="" readonly v-bind="attrs" v-on="on"></v-text-field>
                    </template>
                    <v-date-picker locale="zh" v-model="order.paymentRequestAt"></v-date-picker>
                  </v-menu>
                </v-col>
                <v-col cols="12">
                  <span class="jh-input-label">账单信息</span>
                  <v-card elevation="0">
                    <v-data-table :headers="headers" :items="[order]" :loading="isTableLoading" hide-default-footer
                      class="elevation-0 mt-0 mb-xs-4 flex-fill d-flex flex-column">
                      <template v-slot:item.payment-order="{ item }">
                        {{item.paymentId}}
                      </template>
                      <template v-slot:item.deduction-amount="{ item }">
                        <v-text-field prefix="¥" class="jh-v-input mr-2" dense filled single-line
                          v-model.number="item.deductionAmount" :rules="validationRules.requireRules" type="number">
                        </v-text-field>
                      </template>
                      <template v-slot:item.payment-total-amount="{ item }">
                        {{item.paymentTotalAmount | formatMoney}}
                      </template>
                      <template v-slot:item.payment-paid-amount="{ item }">
                        {{item.paymentPaidAmount | formatMoney}}
                      </template>
                    </v-data-table>
                  </v-card>
                </v-col>

              </v-row>

            </v-expansion-panel-content>
          </v-card>
        </v-expansion-panel>
      </v-expansion-panels>

    </v-form>
    <!-- 抽屉关闭按钮 -->
    <v-btn elevation="0" color="success" fab absolute top left small tile class="drawer-close-float-btn"
      @click="isCreateDrawerShown = false">
      <v-icon>mdi-close</v-icon>
    </v-btn>
  </v-navigation-drawer>
</template>

<script type="module">
  Vue.component("paymentRequest-create", {
    template: '#paymentRequest-create',
    props: {

    },
    data: () => ({
      validationRules: {
        requireRules: [
          v => !!v || '必填',
        ],
        numberRules: [
          v => (!isNaN(v) && parseInt(v) > 0) || '数字必填'
        ]
      },
      constantObj: {},

      isTableLoading: true,
      headers: [
        { text: "账单编号", value: "payment-order", class: 'fixed', cellClass: 'fixed' },
        { text: "账单创建时间", value: "paymentCreateAt" },
        { text: "账单金额", value: "payment-total-amount" },
        { text: "已付款", value: "payment-paid-amount" },
        { text: "本次申请", value: "deduction-amount" },
      ],

      orderIds: [],
      orderList: [],
      actionType: '',
      // 保险付款，保养付款，发车收款，退车付款
      ticketType: '',
      expands: [],

      isCreateDrawerShown: false,
      createActionData: {},
    }),
    async created() {
    },
    async mounted() {
    },
    methods: {
      async doUiAction(uiActionId, uiActionData) {
        try {
          switch (uiActionId) {
            case 'startCreateItem':
              await this.prepareCreateFormData(uiActionData);
              await this.getOrderData();
              await this.openCreateDrawer();
              break;
            case 'createItem':
              await this.prepareCreateValidate();
              await this.confirmCreateItemDialog();
              await this.prepareDoCreateItem();
              await this.doCreateItem();
              await this.closeCreateDrawer();
              break;
            default:
              console.error("[doUiAction] uiActionId not find", { uiActionId });
              break;
          }
        } catch (error) { await window.jhMask.hide(); throw error; }
      },

      // ---------- 初始化数据 uiAction >>>>>>>>>> --------
      async prepareCreateFormData({ orderIds = [], actionType, ticketType }) {
        this.orderIds = orderIds;
        this.actionType = actionType;
        this.ticketType = ticketType;
      },
      // 保险列表
      async getInsuranceList() {
        const rows = (await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'insuranceManagement',
              actionId: 'selectItemList',
              actionData: {},
              whereIn: { insuranceId: this.orderIds },
              orderBy: [{ column: 'idSequence', order: 'desc' }]
            }
          }
        })).data.appData.resultData.rows;
        return rows;
      },
      async getMaintenanceList() {
        const rows = (await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'maintenanceManagement',
              actionId: 'selectItemList',
              actionData: {},
              whereIn: { maintenanceId: this.orderIds },
              orderBy: [{ column: 'idSequence', order: 'desc' }]
            }
          }
        })).data.appData.resultData.rows;
        return rows;
      },
      async getContractList() {
        const rows = (await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'contractManagement',
              actionId: 'selectItemList',
              actionData: {},
              whereIn: { contractId: this.orderIds },
              orderBy: [{ column: 'idSequence', order: 'desc' }]
            }
          }
        })).data.appData.resultData.rows;
        return rows;
      },

      async getOrderData() {
        this.isTableLoading = true;
        let orderList = [];
        if (this.ticketType === '保险付款') {
          orderList = await this.getInsuranceList();
          orderList = _.map(orderList, item => ({
            ...item,
            ticketBizId: item.insuranceId,
            paymentId: item.insuranceId,
            paymentCreateAt: item.insuranceCreateAt,
            paymentTotalAmount: item.insuranceTotalAmount,
            paymentPaidAmount: item.paymentPaidAmount,
            deductionAmount: item.insuranceTotalAmount - (item.paymentPaidAmount || 0),
          }))
        } else if (this.ticketType === '保养付款') {
          orderList = await this.getMaintenanceList();
          orderList = _.map(orderList, item => ({
            ...item,
            ticketBizId: item.maintenanceId,
            paymentId: item.maintenanceId,
            paymentCreateAt: item.maintenanceCreateAt,
            paymentTotalAmount: item.maintenanceTotalAmount,
            paymentPaidAmount: item.paymentPaidAmount,
            deductionAmount: item.maintenanceTotalAmount - (item.paymentPaidAmount || 0),
          }))
        } else if (this.ticketType === '发车收款' || this.ticketType === '退车付款') {
          orderList = await this.getContractList();


          orderList = _.map(orderList, item => {
            // 发车是租金+押金+服务费，退车是退租金
            let paymentTotalAmount = +item.rentAmount + +item.depositAmount + +item.serviceCharge
            let deductionAmount = paymentTotalAmount - (item.receivePaymentPaidAmount || 0)
            if (this.ticketType === '退车付款') {
              paymentTotalAmount = +item.depositAmount
              deductionAmount = paymentTotalAmount - (item.paymentPaidAmount || 0)
            }

            return ({
              ...item,
              ticketBizId: item.contractId,
              paymentId: item.contractId,
              paymentCreateAt: item.contractCreateAt,
              paymentTotalAmount,
              paymentPaidAmount: item.paymentPaidAmount,
              deductionAmount,
            })
          })
        }

        orderList = _.map(orderList, item => ({
          ...item,
          // 测试代码，正面可以注释掉
          customerInfo: {
            customerName: 'xxx',
            customerAccountNum: 'xxx',
            customerBankName: 'xxx',
            customerBranchBankName: 'xxx',
            customerCollectionCycle: 10,
            customerAddress: 'xxx',
            customerContactPerson: 'xxx',
            customerPhoneNum: 'xxx',
            customerPostalCode: 'xxx',
          }
        }))

        this.orderList = orderList
        this.expands = _.map(this.orderList, (item, index) => index);
        this.isTableLoading = false;
      },
      async openCreateDrawer() {
        this.isCreateDrawerShown = true;
      },
      // ---------- <<<<<<<<<<< 初始化数据 uiAction ---------

      // ---------- 新增数据 uiAction >>>>>>>>>> --------
      async prepareCreateValidate() {
        if (await this.$refs.createForm.validate()) {
          return true;
        }
        await window.vtoast.fail("请完善表单信息");
        throw new Error("请完善表单信息")
      },
      async confirmCreateItemDialog() {
        if (await window.confirmDialog({ title: "提交", content: "确定提交吗？" }) === false) {
          throw new Error("[confirmCreateFormDialog] 否");
        }
      },
      prepareDoCreateItem() {
        this.createActionData = _.map(this.orderList, item => {
          return {
            ticketBizId: item.ticketBizId,
            ticketType: this.ticketType,
            ticketContentRequest: {
              ..._.omit(item, ['getCarTicket', 'returnCarTicket', 'customerInfo', 'paymentTicket', 'receiptTicket']),
              customerInfo: _.omit(item.customerInfo, 'productList'),
              paymentRequiredAt: dayjs(item.paymentRequestAt).add(item.customerInfo.customerCollectionCycle, 'day').format('YYYY-MM-DD')
            },
            ticketRequestAmount: item.deductionAmount
          };
        })
      },
      async doCreateItem() {
        await window.vtoast.loading("提交数据");
        await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'ticketManagement',
              actionId: 'createTicket',
              actionData: { dataList: this.createActionData }
            }
          }
        })
        await window.vtoast.success("提交成功");
      },
      async closeCreateDrawer() {
        this.isCreateDrawerShown = false;
        this.createActionData = null;
        this.$emit("success");
      },
      // ---------- <<<<<<<<<<< 新增数据 uiAction ---------
    }
  })
</script>
<style>
  .jh-v-input .v-messages-outer,
  .jh-v-input .v-text-field__details {
    bottom: -15px !important;
  }
</style>